<script type="text/x-template" id="chart">
    <bar-chart :data="chartData"></bar-chart>
</script>
<div id="app">
    <div>
        <span>暗号</span>
        <span>{{anhao}}</span>
    </div>
</div>
<script src="../dist/vue.global.js"></script>
<script>
    const {createApp, createRenderer} = Vue
    const renderer = createRenderer({
        createElement(tag, isSVG, is) {
            return {tag}
        },
        insert(child, parent, anchor) {
            child.parent = parent
            if (!parent.childs) {
                parent.childs = []
            } else {
                parent.childs.push(child)
            }

            if (parent.nodeType === 1) {
                console.log(child)
                draw(child)
            }
        },
        patchProp(el, key, prevValue, nextValue) {
            el[key] = nextValue
        },
        
    })

    let canvas, ctx;
    const draw = (el, noClear) => {
        if (!noClear) {
            ctx.clearRect(0, 0, canvas.width, canvas.height)
        }
        if (el.tag == 'bar-chart') {
            const { data } = el;
            const barWidth = canvas.width / 10,
            gap = 20,
            paddingLeft = (data.length * barWidth + (data.length - 1) * gap) / 2,
            paddingBottom = 10;
            // x轴
            // 柱状图
            data.forEach(({ title, count, color }, index) => {
                const x = paddingLeft + index * (barWidth + gap)
                const y = canvas.height - paddingBottom - count
                ctx.fillStyle = color
                ctx.fillRect(x, y, barWidth, count)
                // text
            });
        }
        // 递归绘制⼦节点
        el.childs && el.childs.forEach(child => draw(child, true));
    }

    function createCanvasApp(App) {
        const app = renderer.createApp(App)
        const mount = app.mount
        app.mount = function(selector) {
            canvas = document.createElement('canvas')
            canvas.width = window.innerWidth
            canvas.height = window.innerHeight

            document.querySelector(selector).appendChild(canvas)

            ctx = canvas.getContext('2d')
            mount(canvas)
        }
        return app
    }

    const app =createCanvasApp({
        template: "#chart",
        data() {
            return {
                chartData: [
                    {title: "one", count: 100, color: "brown"},
                    {title: "two", count: 200, color: "red"},
                    {title: "three", count: 300, color: "blue"},
                ],
                anhao: "mua"
            }
        }
    }).mount('#app')
</script>